package com.ctsi.security.service;

import com.ctsi.commons.event.BaseEvent;
import com.ctsi.commons.event.EventPublisherMan;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.mybatis.support.MybatisGenericDao;
import com.ctsi.organise.common.api.OrganiseFactoryBean;
import com.ctsi.organise.common.api.OrganiseServiceProxy;
import com.ctsi.organise.common.api.UserLoginServiceProxy;
import com.ctsi.organise.common.constant.PartyStatus;
import com.ctsi.organise.common.model.Party;
import com.ctsi.organise.common.model.UserLogin;
import com.ctsi.security.DelRoleException;
import com.ctsi.security.ISecurity;
import com.ctsi.security.OrganiseIn;
import com.ctsi.security.PermissionRole;
import com.ctsi.security.domain.EventDeclaration;
import com.ctsi.security.domain.RolePermission;
import com.ctsi.security.domain.SRole;
import com.ctsi.security.domain.SRoleUser;
import com.ctsi.security.manager.impl.SecurityImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import java.util.*;


/**
 * @author zhangjw
 */
@Repository
public class SRoleService implements PermissionRole {

    private final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SRoleService.class);
    @Autowired
    private UserLoginServiceProxy userLoginService;
    @Autowired
    private MybatisGenericDao dao;
    @Autowired
    private RoleSecurityService roleSecurityService;
    @Autowired
    private OrganiseServiceProxy organiseService;
    @Autowired
    private ISecurity security;
    private String dataObjectType = "sysModule";
    private String action = "SELECT";
    private OrganiseIn organiseIn;
    /**
     * 发布事件
     */
    @Autowired
    private EventPublisherMan publisherMan;

    @Override
    public void setJoinWay(boolean joinWay, SRoleUser sroleUser) {
        if (joinWay) {
            sroleUser.setJoinWay(1);
        } else {
            sroleUser.setJoinWay(0);
        }
    }

    public boolean isJoinWay(SRoleUser sroleUser) {
        return sroleUser.getJoinWay() == 1;
    }

    public MybatisGenericDao getDao() {
        return dao;
    }

    public void setDao(MybatisGenericDao dao) {
        this.dao = dao;
    }

    @Override
    public void addRole(SRole role) {
        Assert.notNull(role);
        String id = role.getRoleId();
        if (UtilValidate.isEmpty(id)) {
            role.setRoleId(UUID.randomUUID().toString());
        }
        dao.insert(role);
        String parentRoleId = role.getParentRoleId();
        if (UtilValidate.isNotEmpty(parentRoleId)) {
            // 父角色的所有功能
            List<RolePermission> rps = roleSecurityService.findRolePermission(new String[]{"roleId"}, new String[]{parentRoleId});
            for (RolePermission rp : rps) {
                rp.setId(UUID.randomUUID().toString());
                rp.setRoleId(role.getRoleId());
                rp.setParentRoleId(parentRoleId);
                dao.insert(rp);
            }
        }
        // dao.saveObject(role);
        // 添加角色发布事件
        Map<String, String> map = new HashMap<String, String>();
        map.put("roleId", role.getRoleId());
        map.put("roleName", role.getRoleName());
        BaseEvent addRoleEvent = new BaseEvent(map, EventDeclaration.addSecurityRole);
        this.publishEvent(addRoleEvent, null);
    }

    @Override
    public void updRole(SRole role) {
        // dao.updateObject(role);
        dao.update(role);
    }


    public void remRole(String roleId) {
        SRole temp = null;
        if (!isRoleEmpty(roleId)) {
            temp = findSRoleById(roleId);
            throw new DelRoleException(temp.getRoleName());
        }
        if (hasSon(roleId)) {
            temp = findSRoleById(roleId);
            throw new DelRoleException(temp.getRoleName());
        }
        // dao.removeObject(com.gentlesoft.security.domain.SRole.class, roleId);
        SRole srole = new SRole();
        srole.setRoleId(roleId);
        dao.remove(srole);
        // 删除角色发布事件
        Map<String, String> map = new HashMap<String, String>();
        map.put("roleId", roleId);
        delSRoleRelData(roleId);
        BaseEvent remRoleEvent = new BaseEvent(map, EventDeclaration.deleteSecurityRole);
        this.publishEvent(remRoleEvent, null);
    }

    private void delSRoleRelData(String roleId) {
        // 清除角色下的功能权限
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(SRole.class.getName());
        stringBuilder.append(".delRoleRlatPerm");
        dao.delete(stringBuilder.toString(), roleId);
        // 清除角色下的数据权限
        StringBuilder stringBuilder2 = new StringBuilder();
        stringBuilder2.append(SRole.class.getName());
        stringBuilder2.append(".delRoleRlatData");
        dao.delete(stringBuilder2.toString(), roleId);
    }

    @Override
    public void updateSoleUserNameByPaytyId(SRoleUser sroleUser) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(SRoleUser.class.getName());
        stringBuilder.append(".updateSoleUserNameByPaytyId");
        dao.update(stringBuilder.toString(), sroleUser);
    }

    /**
     * 查询一个角色下是否有用户、部门或用户组
     *
     * @param roleId
     */
    private boolean isRoleEmpty(String roleId) {

        Assert.notNull(roleId);
        Map<String, Object> params = new HashMap<String, Object>(1);
        params.put("roleId", roleId);
        List<SRoleUser> sru = dao.find(SRoleUser.class, params);
        return !UtilValidate.isNotEmpty(sru);

    }

    private boolean hasSon(String roleId) {
        // 检查是否具有子角色
        List<SRole> srs = getSonRoles(roleId);
        return UtilValidate.isNotEmpty(srs);
    }


    @Override
    public void remRole(List<String> list) {
        for (String roleId : list) {
            this.remRole(roleId);
        }
    }

    /**
     * 查询全部角色信息
     *
     * @return
     */
    public List<SRole> findRoleAll() {
        // String hsql = "from com.gentlesoft.security.domain.SRole";
        // return dao.findAll(hsql);
        return dao.find(SRole.class, (Map<String, Object>) null);
    }

    private void insertRoleUser(SRoleUser roleUser) {
        Assert.notNull(roleUser);
        String roleUserId = roleUser.getRoleUserId();
        if (UtilValidate.isEmpty(roleUserId)) {
            roleUser.setRoleUserId(UUID.randomUUID().toString());
        }
        dao.insert(roleUser);
    }

    @Override
    public Page queryRoleUser(int pageSize, int startIndex, String roleId, String userLoginId, String userLoginName,String curLoginId) {
        Assert.notNull(roleId);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("roleId", roleId);
        if (UtilValidate.isNotEmpty(userLoginId)) {
            userLoginId = "%" + userLoginId + "%";
            params.put("loginId", userLoginId);
        }
        if (UtilValidate.isNotEmpty(userLoginName)) {
            userLoginName = "%" + userLoginName + "%";
            params.put("loginName", userLoginName);
        }
        if (UtilValidate.isEmpty(userLoginId) && UtilValidate.isEmpty(userLoginName)) {
            params.put("joinWay", SRoleUser.joinWayDefault);
        }
        if (!security.isControl(curLoginId,"organChain","SELECT")) {
            return dao.queryPage(SRoleUser.class.getName() + ".queryForCon", params, startIndex, pageSize);
        } else {
            Set<String> dataObjectIds = security.findDataObjectIds(curLoginId,"organChain","SELECT");
            if (UtilValidate.isEmpty(dataObjectIds)) {
                //long start, long totalSize, int pageSize, List<E> data
                return new Page(startIndex,0,pageSize,Collections.emptyList());
            }
            params.put("dataObjectIds",dataObjectIds);
            return dao.queryPage(SRoleUser.class.getName() + ".queryForCon", params, startIndex, pageSize);
        }
    }

    public void addRoleUser(String roleId, SRoleUser sroleUser, boolean joinWay) {
        Assert.notNull(sroleUser);
        String roleUserId = sroleUser.getRoleUserId();
        if (UtilValidate.isEmpty(roleUserId)) {
            sroleUser.setRoleUserId(UUID.randomUUID().toString());
        }
        sroleUser.setRoleId(roleId);
        sroleUser.setType(SRoleUser.typeUser);
        // 根据roleId和partyId查询是否有数据，有数据更新,没有数据插入
        List<SRoleUser> listSRoleUser = this.findRoleUser(new String[]{"roleId", "partyId", "loginId"}, new Object[]{roleId, sroleUser.getPartyId(), sroleUser.getLoginId()});
        if (listSRoleUser.size() > 0) {
            SRoleUser local = listSRoleUser.get(0);
            local.setRefCount(local.getRefCount() + 1);
            if (!joinWay) {
                setJoinWay(SRoleUser.joinWayHand, local);
            }
            dao.update(local);
        } else {
            sroleUser.setRefCount(1);
            setJoinWay(joinWay, sroleUser);
            // dao.saveObject(sroleUser);
            // dao.insert(sroleUser);
            insertRoleUser(sroleUser);
            // 发布事件
            Map<String, Object> map = new HashMap<String, Object>();
            List<String> list = new ArrayList<String>();
            list.add(sroleUser.getLoginId());
            map.put("listUserLoginId", list);
            BaseEvent baseEvent = new BaseEvent(this, "securityUserRole", map);
            this.publishEvent(baseEvent, null);
            // 单独发布角色添加登陆用户事件
            Map<String, String> roleUserLogin = new HashMap<String, String>();
            roleUserLogin.put("roleId", roleId);
            roleUserLogin.put("userLoginId", sroleUser.getLoginId());
            roleUserLogin.put("userLoginName", sroleUser.getLoginName());
            BaseEvent newBE = new BaseEvent(roleUserLogin, EventDeclaration.securityRoleAddUser);
            this.publishEvent(newBE, null);
        }
    }

    @Override
    public void addRoleOrgan(String roleId, SRoleUser sroleUser, boolean joinWay, String type) {
        sroleUser.setRoleId(roleId);
        sroleUser.setType(type);
        // 根据roleId和partyId查询是否有数据，有数据更新,没有数据插入
        List<SRoleUser> listSRoleUser = this.findRoleUser(new String[]{"roleId", "partyId"}, new Object[]{roleId, sroleUser.getPartyId()});
        if (listSRoleUser.size() > 0) {
            SRoleUser local = listSRoleUser.get(0);
            local.setRefCount(local.getRefCount() + 1);
            if (!joinWay) {
                setJoinWay(SRoleUser.joinWayHand, local);
            }
            dao.update(local);
        } else {
            sroleUser.setRefCount(1);
            setJoinWay(joinWay, sroleUser);
            // dao.saveObject(sroleUser);
            // dao.insert(sroleUser);
            insertRoleUser(sroleUser);
        }
    }

    @Override
    public void addRoleUserGroup(String roleId, SRoleUser insertRoleUser) {
        // dao.insert(sroleUser);
        insertRoleUser(insertRoleUser);
    }

    @Override
    public void addRoleOrganAndUser(String roleId, List<SRoleUser> listOrgan, List<SRoleUser> listUser, String type) {
        // 添加组织
        for (SRoleUser organ : listOrgan) {
            this.addRoleOrgan(roleId, organ, true, SRoleUser.typeOrgan);
        }
        // 添加用户
        for (SRoleUser user : listUser) {
            this.addRoleUser(roleId, user, true);
            // 清除用户的缓存
            SecurityImpl.removeCacheUserRoles(user.getLoginId());
        }
    }

    @Override
    public void remRoleUser(String partyId, String loginId, boolean joinWay, String roleId) {
        // 取出数据根据refCount判断是删除还是更新
        List<SRoleUser> listUser = this.findRoleUser(new String[]{"roleId", "partyId", "loginId"}, new Object[]{roleId, partyId, loginId});
        if (listUser.size() > 0) {
            SRoleUser sroleUser = listUser.get(0);
            if (sroleUser.getRefCount() > 1) {// 更新
                sroleUser.setRefCount(sroleUser.getRefCount() - 1);
                if (!joinWay)
                    setJoinWay(SRoleUser.joinWayAuto, sroleUser);
                // dao.updateObject(sroleUser);
                dao.update(sroleUser);
            } else {// 删除
                // dao.removeObject(com.gentlesoft.security.domain.SRoleUser.class,
                // sroleUser.getRoleUserId());

                dao.remove(sroleUser);
                // 发布事件
                Map<String, Object> map = new HashMap<String, Object>();
                List<String> list = new ArrayList<String>();
                list.add(loginId);
                map.put("listUserLoginId", list);
                BaseEvent baseEvent = new BaseEvent(this, "securityUserRole", map);
                this.publishEvent(baseEvent, null);
                Map<String, String> newMap = new HashMap<String, String>();
                newMap.put("roleId", roleId);
                newMap.put("userLoginId", loginId);
                BaseEvent newBe = new BaseEvent(newMap, EventDeclaration.securityRoleDeleteUser);
                this.publishEvent(newBe, null);
            }
        }
    }

    @Override
    public void remRoleOrganAndUserGroup(String partyId, boolean joinWay, String roleId) {
        // 取出数据根据refCount判断是删除还是更新
        List<SRoleUser> listUser = this.findRoleUser(new String[]{"roleId", "partyId"}, new Object[]{roleId, partyId});
        if (listUser.size() > 0) {
            SRoleUser sroleUser = listUser.get(0);
            if (sroleUser.getRefCount() > 1) {// 更新
                sroleUser.setRefCount(sroleUser.getRefCount() - 1);
                if (!joinWay)
                    setJoinWay(SRoleUser.joinWayAuto, sroleUser);
                // dao.updateObject(sroleUser);
                dao.update(sroleUser);
            } else {// 删除
                // dao.removeObject(com.gentlesoft.security.domain.SRoleUser.class,
                // sroleUser.getRoleUserId());
                dao.remove(sroleUser);
            }
        }
    }

    @Override
    public void remRoleAllOrganAndUserGroup(String partyId, String roleId, String type) {
        // 删除当前组织或用户组
        this.remRoleOrganAndUserGroup(partyId, false, roleId);
        // 取所有的子组织并删除
        List<SRoleUser> listOrganAndUserGroup = organiseIn.getOrganOrUserGroupToOrgan(partyId, type);
        for (SRoleUser sroleUser : listOrganAndUserGroup) {
            this.remRoleOrganAndUserGroup(sroleUser.getPartyId(), true, roleId);
        }
        // 取所有的用户并删除
        List<SRoleUser> listUser = organiseIn.getOrganOrUserGroupToLoginUser(partyId, type);
        for (SRoleUser sroleUser : listUser) {
            this.remRoleUser(sroleUser.getPartyId(), sroleUser.getLoginId(), true, roleId);
            // 清除缓存
            SecurityImpl.removeCacheUserRoles(sroleUser.getLoginId());
        }
    }


    @Override
    public List<SRoleUser> findRoleUser(String[] field, Object[] args) {

        if (field == null || args == null) {
            return new ArrayList<SRoleUser>(0);
        }
        Assert.isTrue(field.length == args.length);
        Map<String, Object> params = new HashMap<String, Object>(field.length);
        for (int i = 0; i < field.length; i++) {
            params.put(field[i], args[i]);
        }
        return dao.find(SRoleUser.class, params);

    }

    @Override
    public SRole findSRoleById(String roleId) {
        // return dao.findUniqueBy(SRole.class,"roleId", roleId);
        return dao.get(SRole.class, roleId);
    }

    @Override
    public List<String> findRoleUserLoginId(String[] field, Object[] args) {

        if (field == null || args == null) {
            return new ArrayList<String>(0);
        }
        Assert.isTrue(field.length == args.length);
        Map<String, Object> params = new HashMap<String, Object>(field.length);
        for (int i = 0; i < field.length; i++) {
            params.put(field[i], args[i]);
        }
        List<SRoleUser> temp = dao.find(SRoleUser.class, params);
        if (UtilValidate.isNotEmpty(temp)) {
            List<String> result = new ArrayList<String>(temp.size());
            for (SRoleUser roleUser : temp) {
                result.add(roleUser.getLoginId());
            }
            return result;
        } else {
            return new ArrayList<String>(0);
        }

    }

    @Override
    public boolean valRoleName(String roleName) {

        Map<String, Object> params = new HashMap<String, Object>(1);
        params.put("roleName", roleName);
        List<SRole> temp = dao.find(SRole.class, params);
        return !UtilValidate.isEmpty(temp);
    }

    @Override
    public int saveOrganAndUserGroup(String roleId, String type, String[] arrayPartyId, String[] arrayLoginName) {
        for (int i = 0; i < arrayPartyId.length; i++) {
            String partyId = arrayPartyId[i];
            String partyName = arrayLoginName[i];
            partyId = partyId == null ? "" : partyId.trim();
            partyName = partyName == null ? "" : partyName.trim();
            if (!partyId.equals("")) {
                // 这里得到的组织或用户组，都是树上选择的都认为是手动添加,先判断是否已经手动添加过，已经存在，返回提示已经添加
                List<SRoleUser> listlocal = this.findRoleUser(new String[]{"roleId", "partyId", "joinWay"}, new Object[]{roleId, partyId, SRoleUser.joinWayDefault});
                if (listlocal.size() > 0) {
                    logger.error("权限角色{}已存在:{}", roleId, arrayLoginName[i]);
                    throw new RuntimeException("权限角色" + roleId + "已存在" + arrayLoginName[i]);
                }
                // 取组织下的所有子组织
                List<SRoleUser> listOrgan = organiseIn.getOrganOrUserGroupToOrgan(partyId, type);
                // 取组织下的所有用户
                List<SRoleUser> listUser = organiseIn.getOrganOrUserGroupToLoginUser(partyId, type);
                // 加入的当前组织
                SRoleUser sroleUser = new SRoleUser();
                sroleUser.setLoginName(partyName);
                sroleUser.setPartyId(partyId);
                setJoinWay(SRoleUser.joinWayHand, sroleUser);
                sroleUser.setRefCount(1);
                sroleUser.setType(type);
                // 手动添加当前组织或用户组
                this.addRoleOrgan(roleId, sroleUser, false, type);
                // 添加当前组织下的子组织和用户
                this.addRoleOrganAndUser(roleId, listOrgan, listUser, type);
            }
        }
        return -1;
    }


    @Override
    public List<Integer> saveOrganAndUserGroup(String type, String[] arrayPartyId, String[] arrayLoginName, String roleId) {
        List<Integer> error = new ArrayList<Integer>();
        for (int i = 0; i < arrayPartyId.length; i++) {
            String partyId = arrayPartyId[i];
            String partyName = arrayLoginName[i];
            partyId = partyId == null ? "" : partyId.trim();
            partyName = partyName == null ? "" : partyName.trim();
            if (!partyId.equals("")) {
                // 这里得到的组织或用户组，都是树上选择的都认为是手动添加,先判断是否已经手动添加过，已经存在，返回提示已经添加
                List<SRoleUser> listlocal = this.findRoleUser(new String[]{"roleId", "partyId", "joinWay"}, new Object[]{roleId, partyId, SRoleUser.joinWayDefault});
                if (listlocal.size() > 0) {
                    logger.warn("权限角色{}已存在组织:{}", roleId, arrayLoginName[i]);
                    error.add(i);
                    continue;
                }
                // 取组织下的所有子组织
                List<SRoleUser> listOrgan = organiseIn.getOrganOrUserGroupToOrgan(partyId, type);
                // 取组织下的所有用户
                List<SRoleUser> listUser = organiseIn.getOrganOrUserGroupToLoginUser(partyId, type);
                // 加入的当前组织
                SRoleUser sroleUser = new SRoleUser();
                sroleUser.setLoginName(partyName);
                sroleUser.setPartyId(partyId);
                setJoinWay(SRoleUser.joinWayHand, sroleUser);
                sroleUser.setRefCount(1);
                sroleUser.setType(type);
                // 手动添加当前组织或用户组
                this.addRoleOrgan(roleId, sroleUser, false, type);
                // 添加当前组织下的子组织和用户
                this.addRoleOrganAndUser(roleId, listOrgan, listUser, type);
            }
        }
        return error;
    }


    @Override
    public int delSRoleUser(String[] arrayRoleUserId, String[] arrayLoginId, String[] arrayPartyId, String[] arrayType, String roleId) {
        for (int i = 0; i < arrayRoleUserId.length; i++) {
            String type = arrayType[i] == null ? "" : arrayType[i].trim();
            if (type.equals(SRoleUser.typeUser)) {
                this.remRoleUser(arrayPartyId[i], arrayLoginId[i], false, roleId);
            } else if (type.equals(SRoleUser.typeOrgan)) {
                this.remRoleAllOrganAndUserGroup(arrayPartyId[i], roleId, SRoleUser.typeOrgan);
            } else {
                this.remRoleAllOrganAndUserGroup(arrayPartyId[i], roleId, SRoleUser.typeUserGroup);
            }

        }
        return -1;
    }

    @Override
    public int saveAllRoleUser(String roleId, String[] arrayLoginId, String[] arrayLoginName, String[] arrayParty) {
        for (int i = 0; i < arrayLoginId.length; i++) {
            SRoleUser sroleUser = new SRoleUser();
            // 根据roleId和userId判断是否存在该记录
            List<SRoleUser> list = this.findRoleUser(new String[]{"roleId", "loginId", "joinWay"}, new Object[]{roleId, arrayLoginId[i], SRoleUser.joinWayDefault});
            if (list.size() > 0) {
                logger.error("权限角色{}已存在用户:{}", roleId, arrayLoginName[i]);
                throw new RuntimeException("权限角色" + roleId + "已存在用户" + arrayLoginName[i]);
            }
            sroleUser.setRoleId(roleId);
            sroleUser.setLoginId(arrayLoginId[i]);
            sroleUser.setLoginName(arrayLoginName[i]);
            sroleUser.setPartyId(arrayParty[i]);
            this.addRoleUser(roleId, sroleUser, false);
        }
        return -1;
    }


    @Override
    public List<Integer> saveAllRoleUser(String[] arrayLoginId, String[] arrayLoginName, String[] arrayParty, String roleId) {
        List<Integer> error = new ArrayList<Integer>();
        for (int i = 0; i < arrayLoginId.length; i++) {
            SRoleUser sroleUser = new SRoleUser();
            UserLogin userLogin = getUserLoginService().findById(arrayLoginId[i]);
            // 根据roleId和userId判断是否存在该记录
            List<SRoleUser> list = this.findRoleUser(new String[]{"roleId", "loginId", "joinWay"}, new Object[]{roleId, userLogin.getId(), SRoleUser.joinWayDefault});
            if (list.size() > 0) {
                logger.warn("权限角色{}已存在用户:{}", roleId, arrayLoginName[i]);
                error.add(i);
                continue;
            }
            sroleUser.setRoleId(roleId);
            sroleUser.setLoginId(userLogin.getId());
            sroleUser.setLoginName(arrayLoginName[i]);
            sroleUser.setPartyId(arrayParty[i]);
            this.addRoleUser(roleId, sroleUser, false);
        }
        return error;
    }


    @Override
    public List<Integer> saveAllRoleUserWithLoginId(String[] arrayLoginId, String[] arrayLoginName, String[] arrayParty, String roleId) {
        List<Integer> error = new ArrayList<Integer>();
        for (int i = 0; i < arrayLoginId.length; i++) {
            SRoleUser sroleUser = new SRoleUser();

            // 根据roleId和userId判断是否存在该记录
            List<SRoleUser> list = this.findRoleUser(new String[]{"roleId", "loginId", "joinWay"}, new Object[]{roleId, arrayLoginId[i], 0});
            if (list.size() > 0) {
                logger.warn("权限角色{}已存在用户:{}", roleId, arrayLoginName[i]);
                error.add(i);
                continue;
            }
            sroleUser.setRoleId(roleId);
            sroleUser.setLoginId(arrayLoginId[i]);
            sroleUser.setLoginName(arrayLoginName[i]);
            sroleUser.setPartyId(arrayParty[i]);
            this.addRoleUser(roleId, sroleUser, false);
        }
        return error;
    }

    /**
     * 发布事件
     *
     * @param baseEvent
     * @param args
     */
    private void publishEvent(BaseEvent baseEvent, Object args) {
        publisherMan.getEventPublisher().publishEvent(baseEvent, args);
    }


    public void setPublisherMan(EventPublisherMan publisherMan) {
        this.publisherMan = publisherMan;
    }

    public OrganiseIn getOrganiseIn() {
        return organiseIn;
    }

    public void setOrganiseIn(OrganiseIn organiseIn) {
        this.organiseIn = organiseIn;
    }

    @Override

    public List<String> getRoleIdsByPartyId(String partyId) {
        // String hsql="select roleId from SRoleUser where partyId=?";
        // return dao.findAll(hsql, partyId);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("partyId", partyId);
        List<SRoleUser> result = dao.find(SRoleUser.class, params);
        if (UtilValidate.isNotEmpty(result)) {
            List<String> result1 = new ArrayList<String>(result.size());
            for (SRoleUser roleUser : result) {
                result1.add(roleUser.getRoleId());
            }
            return result1;
        } else {
            return new ArrayList<String>(0);
        }
    }

    @Override
    public void delUserRoles(String loginId, String roleIds) {
        String[] roleItems = roleIds.split(",");
        for (String roleId : roleItems) {
            delUserRole(loginId, roleId);
        }

    }

    @Override
    public void refresh(String roleId) {
        List<SRoleUser> list = (List<SRoleUser>) dao.queryForList(SRoleUser.class.getName() + ".refreshselect", roleId);
        dao.delete(SRoleUser.class.getName() + ".refreshdelete", roleId);
        for (SRoleUser sRoleUser : list) {
            if (sRoleUser.getType().equals(SRoleUser.typeUser)) {

                Party party = OrganiseFactoryBean.getInstance().getPersonServiceProxy().findPersonById(sRoleUser.getPartyId());
                if (party == null || party.getStatusId().equalsIgnoreCase(PartyStatus.deleted.value)) {
                    continue;
                }
                saveAllRoleUserWithLoginId(new String[]{sRoleUser.getLoginId()}, new String[]{sRoleUser.getLoginName()}, new String[]{sRoleUser.getPartyId()}, sRoleUser.getRoleId());
            } else {
                Party party = getOrganiseService().findOrganiseById(sRoleUser.getPartyId());
                if (party == null || party.getStatusId().equalsIgnoreCase(PartyStatus.deleted.value)) {
                    continue;
                }
                this.saveOrganAndUserGroup(SRoleUser.typeOrgan, new String[]{sRoleUser.getPartyId()}, new String[]{sRoleUser.getLoginName()}, sRoleUser.getRoleId());
            }

        }
        SecurityImpl.removeCacheRole(null);
        SecurityImpl.removeCacheUserRoles(null);
    }

    @Override
    public void delUserRole(String loginId, String roleId) {
        Map<String, Object> args = new HashMap<String, Object>();
        args.put("loginId", loginId);
        args.put("roleId", roleId);
        dao.delete(SRoleUser.class.getName() + ".delUserRole", args);
        // 清除缓存
        SecurityImpl.removeCacheUserRoles(loginId);
    }

    /**
     * 增加用户角色（可多个角色，","分割）
     *
     * @param loginId
     * @param loginName
     * @param roleIds
     */
    public void addUserRoles(String loginId, String loginName, String partyId, String roleIds) {
        String[] roleItems = roleIds.split(",");
        for (String roleId : roleItems) {
            addUserRole(loginId, loginName, partyId, roleId);
        }
    }

    @Override
    public void addUserRole(String loginId, String loginName, String partyId, String roleId) {
        SRoleUser sroleUser = new SRoleUser();
        setJoinWay(SRoleUser.joinWayHand, sroleUser);
        sroleUser.setLoginId(loginId);
        sroleUser.setLoginName(loginName);
        sroleUser.setPartyId(partyId);
        sroleUser.setRefCount(1);
        sroleUser.setRoleId(roleId);
        sroleUser.setType(SRoleUser.typeUser);
        sroleUser.setRoleUserId(UUID.randomUUID().toString());
        addRoleUser(roleId, sroleUser, SRoleUser.joinWayHand);
        // 清除缓存
        SecurityImpl.removeCacheUserRoles(loginId);

    }

    @Override
    public void addSRoleMem(SRole role, String loginUserIds, String loginNames, String partyIds, String organIds, String organNames, String groupIds, String groupNames) {
        Assert.notNull(role);
        // 保存角色信息
        addRole(role);
        // 角色ID
        String roleId = role.getRoleId();
        // 增加登录用户
        if (UtilValidate.isNotEmpty(loginUserIds)) {
            String[] loginUserId = loginUserIds.split(",");
            String[] names = loginNames.split(",");
            List<String> listId = new ArrayList<String>();
            List<String> listName = new ArrayList<String>();
            List<String> listParty = new ArrayList<String>();
            for (int i = 0; i < loginUserId.length; i++) {
                UserLogin login = getUserLoginService().findById(loginUserId[i]);
                if (login == null) {
                    continue;
                }
                listId.add(login.getId());
                listName.add(names[i]);
                listParty.add(login.getPartyId());
            }
            saveAllRoleUser(roleId, listId.toArray(new String[0]), listName.toArray(names), listParty.toArray(new String[0]));
        }
        // 增加部门
        if (UtilValidate.isNotEmpty(organIds)) {
            saveOrganAndUserGroup(roleId, SRoleUser.typeOrgan, organIds.split(","), organNames.split(","));
        }

        // 增加用户组
        if (UtilValidate.isNotEmpty(groupIds)) {
            saveOrganAndUserGroup(roleId, SRoleUser.typeUserGroup, groupIds.split(","), groupNames.split(","));
        }
    }

    /**
     * 根据角色ID列表查询符合条件的权限角色对象列表
     *
     * @param roleIds
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<SRole> findSRoleByIds(List<String> roleIds) {
        if (UtilValidate.isNotEmpty(roleIds)) {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("roleIds", roleIds);
            return (List<SRole>) dao.queryForList(SRole.class.getName() + ".querySrolesByIds", param);
        } else {
            return new ArrayList<SRole>();
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<SRole> getSonRoles(String parentRoleId) {
        if (parentRoleId == null) {
            return (List<SRole>) dao.queryForList(SRole.class.getName() + ".querySonRoles");
        }
        return (List<SRole>) dao.queryForList(SRole.class.getName() + ".querySonRoles", parentRoleId);
    }

    @Override
    public List<SRole> getSonRoles(String parentRoleId, String loginId) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("parentRoleId", parentRoleId);
        if (security.isControl(loginId, dataObjectType, action)) {
            List<String> dataObjectIds = security.getDataObjectIds(loginId, dataObjectType, action);
            if (UtilValidate.isEmpty(dataObjectIds)) {
                return new ArrayList<SRole>();
            }
            param.put("dataObjectIds", dataObjectIds);
        }
        return (List<SRole>) dao.queryForList(SRole.class.getName() + ".querySonRolesWithDataObject", param);
    }

    @Override
    public List<SRole> getModuleTypeRoles(String moduleType) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("moduleType", moduleType);
        if (moduleType == null) {
            return (List<SRole>) dao.queryForList(SRole.class.getName() + ".querySRoleByModuleType");
        }
        return (List<SRole>) dao.queryForList(SRole.class.getName() + ".querySRoleByModuleType", param);
    }

    public List<SRole> getModuleTypeRoles(String moduleType, String secondModuleType) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("moduleType", moduleType);
        param.put("secondModuleType", secondModuleType);
        return (List<SRole>) dao.queryForList(SRole.class.getName() + ".querySRoleByModuleType", param);
    }

    @Override
    public List<SRole> getDesRoles(String roleId) {
        List<SRole> result = new ArrayList<SRole>();
        List<SRole> children = getSonRoles(roleId);
        if (UtilValidate.isNotEmpty(children)) {
            result.addAll(children);
            for (SRole srole : children) {
                result.addAll(getSonRoles(srole.getRoleId()));
            }
        }
        return result;
    }

    public OrganiseServiceProxy getOrganiseService() {
        if (organiseService == null) {
            organiseService = OrganiseFactoryBean.getInstance().getOrganiseProxy();
        }

        return organiseService;
    }

    public void setOrganiseService(OrganiseServiceProxy organiseService) {
        this.organiseService = organiseService;
    }

    public ISecurity getSecurity() {
        return security;
    }


    public void setSecurity(ISecurity security) {
        this.security = security;
    }

    public String getDataObjectType() {
        return dataObjectType;
    }

    public void setDataObjectType(String dataObjectType) {
        this.dataObjectType = dataObjectType;
    }


    public String getAction() {
        return action;
    }

    public void setAction(String action) {
        this.action = action;
    }

    public UserLoginServiceProxy getUserLoginService() {
        if (userLoginService == null) {
            userLoginService = OrganiseFactoryBean.getInstance().getUserLoginProxy();
        }

        return userLoginService;
    }

    public void setUserLoginService(UserLoginServiceProxy userLoginService) {
        this.userLoginService = userLoginService;
    }


}
